/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.Course;
import models.User;
import org.hibernate.Session;
import service.CategoryDao;
import service.CourseDao;
import service.HibernateUtil;
import service.UserDao;

/**
 *
 * @author kjeld
 */
public class CourseListController extends HttpServlet {

    private HibernateUtil HU = new HibernateUtil();
    private Session session = HU.openSession();
    private CourseDao dao = new CourseDao(session);
    private UserDao udao = new UserDao(session);
    private CategoryDao cdao = new CategoryDao(session);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        long userID = 0;
        HttpSession sessie = request.getSession(true);
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals("userID")) {
                if (cookie.getValue().length() > 0) {
                    userID = Long.parseLong(cookie.getValue());
                    sessie.setAttribute("loggedin", "true");
                }
            }
        }
        HU = new HibernateUtil();
        session = HU.openSession();
        List<Course> courses = dao.findAll();
        
        if (userID != 0) {
            
            User user = udao.get(userID);
            
            try{
            Set<Course> coursesFromUser = user.getStudentCourses();
            sessie.setAttribute("coursesFromUser", coursesFromUser);
            System.out.println("courses" + coursesFromUser);
            System.out.println("Courses from user: " + coursesFromUser.size());
            
            for (Course course : coursesFromUser) {
                System.out.println("course: " + course.getName());
                courses.remove(course);
            }
            }catch(Exception e){
                System.out.println(e);
            }
            
            
        }
        sessie.setAttribute("courses", courses);
        RequestDispatcher dispatcher = request.getRequestDispatcher("courses.jsp");
        dispatcher.forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }
}
